'use strict';
const Service = require('egg').Service;
const AlipaySdk = require('alipay-sdk').default;

class CartService extends Service {
  async getAllRelation(uid) {
    const res = await this.app.mysql.query('SELECT * FROM `userlecture_R_cart` JOIN `class` ON `lecture_id` = `class_id` WHERE `user_id` = ? and `ava` = ?', [ uid, 1 ]);
    console.log(res);
    const cutid = res.map(val => {
      return {
        lecture_id: val.lecture_id,
        buy: val.buy,
        learn: val.learn,
        progress: val.progress,
        classname: val.classname,
        brief: val.brief,
        price: val.price,
        startpic: val.startpic,
      };
    });
    return cutid;
  }

  async addInCart(uid, lid) {
    const res1 = await this.app.mysql.get('userlecture_R_cart', {
      user_id: uid,
      lecture_id: lid,
    });

    if (res1) { // 显然是已经添加到购物车了
      return {
        code: 1,
        err: 'ITEM_EXIST_IN_CART',
      };
    }
    const res2 = await this.app.mysql.insert('userlecture_R_cart', {
      user_id: uid,
      lecture_id: lid,
    });
    return {
      code: 0,
      sqlPacket: res2,
    };
  }
  async getOrderResult(orderid, uid) {
    const alipaySdk = new AlipaySdk({
      appId: this.config.alipay.appId,
      privateKey: this.config.alipay.privateKey,
      alipayPublicKey: this.config.alipay.alipayPublicKey,
      dev: true,
    });
    const res = await this.app.mysql.query('SELECT * FROM `order` WHERE user_id = ? and order_id = ?',[ uid, orderid ]);
    if (res && res.length > 0) {
      const queryres = await alipaySdk.exec('alipay.trade.query', {
        bizContent: {
          out_trade_no: orderid,
        },
      });
      if (queryres && queryres.code === '10000' && queryres.tradeStatus === 'TRADE_SUCCESS') {
        const items = await this.orderItems(orderid);
        const ownRes = await this.service.lecturer.ownTheLecture(items, uid);
        console.log(ownRes);
        return {
          code: 0,
          status: queryres.tradeStatus,
        };
      }
      return {
        code: 0,
        status: queryres.tradeStatus,
      };
    }
    return {
      code: 1001,
      status: 'USERID_NO_COMPARE',
    };

  }
  async orderItems(orderId) {
    let res = await this.app.mysql.select('orderlecture_R', {
      where: {
        order_id: orderId,
      },
    });
    res = res.map(val => {
      return { lectureId: val.lecture_id };
    });
    return res;
  }

  /**
   * 用于创建订单
   * @param {array} cart - an array of item id
   * @param {string} orderid - order_id
   * @param {int} amount - the fee
   * @param {string} uid - 用户id
   */
  async orderCreate(cart, orderid, amount, uid) {
    const conn = await this.app.mysql.beginTransaction();
    try {
      await conn.insert('order',{
        state: 0,
        fee: amount,
        user_id: uid,
        order_id: orderid,
      });
      for (let i=0; i < cart.length; i++) {
        await conn.insert('orderlecture_R',{
          order_id: orderid,
          lecture_id: cart[i].id,
        });
      }
      await conn.commit();
    } catch (err) {
      await conn.rollback(); // 一定记得捕获异常后回滚事务！！
      throw err;
    }

  }
}
module.exports = CartService;
